new Vue({
  el: "#app",
  data() {
    const Pass_Word = (rule, value, callback) => {
      if (validatePassword(this.form.Pass_Word)) {
        callback(new Error(validatePassword(this.form.Pass_Word)));
      } else {
        callback();
      }
    };
    const User_Number = (rule, value, callback) => {
      if (!validatemobile(this.form.User_Number)) {
        callback(new Error("请输入有效手机号"));
      } else {
        callback();
      }
    };
    return {
      use: decodeURI($.cookie("use")),
      iJSONArray_Variety: [],
      iJSONArray_VarietyGrade: [],
      VarietyID: "",
      GradeID: "",
      PurchaseDate: "",
      Unit: "",
      sfzh: {},
      options: [
        {
          value: "斤",
          label: "斤",
        },
        {
          value: "公斤",
          label: "公斤",
        },
        {
          value: "千克",
          label: "千克",
        },
        {
          value: "克",
          label: "克",
        },
        {
          value: "吨",
          label: "吨",
        },
      ],
      PurchaseQuantity: 1,
      PurchasePrice: 1,
      form: {
        ID_Number: "",
        ID_Name: "",
        ID_Front: "",
        ID_Back: "",
        Phone: "",
        Validity_EndDate: "",
        ID_Address: "",
        ProvinceNumber: "",
        CityNumber: "",
        CountyNumber: "",
        TownNumber: "",
        VillageNumber: "",
        value1: [],
        town: [], //市区
        value2: [],
      },
      land: [
        {
          Traceability_Land_SerialNumber: "",
          ID_Number: "",
          Land_Number: "",
          ProvinceNumber: "",
          CityNumber: "",
          CountyNumber: "",
          TownNumber: "",
          VillageNumber: "",
          Located: "",
          Planting_Area: "",
          Category_SerialNumber: "",
          Land_Certificate: "",
          longitude: "",
          latitude: "",
          TownJSON: "",
          value1: [],
          town: [], //市区
          value2: [],
        },
      ],
      rules: {
        Phone: [
          {
            required: true,
            message: "请输入联系方式",
            trigger: "blur",
          },
          {
            pattern: /^1[3-9]\d{9}$/,
            message: "请输入正确的手机号",
            trigger: "blur",
          },
        ],
      },
      iconLoading: false,
      city: [], //城市
      value: [],
      category: [],
      address: "",
      loading: false,
    };
  },
  mounted() {
    console.log(this.use);
    // sessionStorage.setItem("PurchaseEnterpriseID", this.use);
    this.getData();
    this.getVarietyList();
  },
  watch: {
    "form.ID_Number"(val) {
      this.land.forEach((item) => {
        item.ID_Number = val;
      });
    },
    "form.ID_Front"(Data) {
      const that = this;
      that.iconLoading = true;
      $.ajax({
        url: `${BASE_URL1}/parseIDCardAction`,
        type: "POST",
        data: { Data },
        success: function (Result) {
          console.log(Result);
          if (Result.Status == "success") {
            if (typeof Result.ID_Number !== "undefined") {
              that.$message({
                message: "识别成功",
                type: "success",
              });
              that.form.ID_Number = Result.ID_Number;
              that.form.ID_Name = Result.name;
              let reg = /.+?(省|市|自治区|自治州|县|区)/g;
              let arr = Result.address.match(reg);
              let obj1 = that.city.filter(
                (i) => i.children && i.children.some((x) => x.label == arr[0])
              )[0];
              let obj2 = obj1.children.filter((i) => i.label == arr[0])[0];
              let obj3 = obj2.children.filter((i) => i.label == arr[1])[0];
              let arr1 = [];
              if (obj1) {
                arr1 = [obj1.value];
                if (obj2) {
                  arr1 = [...arr1, obj2.value];
                  if (obj3) {
                    arr1 = [...arr1, obj3.value];
                  }
                }
              }
              that.form.value1 = arr1;
            } else {
              that.$message.error("未识别到");
            }
          } else {
            that.$message.error("内容解析出错");
          }
        },
        fail: (err) => {
          that.$message.error("识别失败");
          console.error(err);
        },
        complete: function () {
          that.iconLoading = false;
        },
        dataType: "json",
      });
    },
    "form.VillageNumber"(val) {
      if (val) {
        // let str = this.form.
      }
    },
  },
  methods: {
    getVarietyList() {
      const _this = this;
      $.ajax({
        headers: requestHeaders(),
        // url: `${BASE_URL2}/generalBusiness/generalPaginationQueryBySQLSerialNumber`,
        url: "https://service.kdddy.cn/donghui/generalBusiness/generalQueryByTableName",
        type: "POST",
        data: {
          Data: "base_EdibleMushroomVariety",
          Condition: "Row_Status='0'",
        },
        success: function (Result) {
          console.log(Result, "--------------");

          _this.iJSONArray_Variety = Result;
        },
        complete: function (XMLHttpRequest) {
          requestPretreatment(XMLHttpRequest); //config/config.js 响应预检
        },
        dataType: "json",
      });
    },
    dj(value) {
      console.log(value, "value");

      // return;
      const _this = this;
      $.ajax({
        headers: requestHeaders(),
        // url: `${BASE_URL2}/generalBusiness/generalPaginationQueryBySQLSerialNumber`,
        url: "https://service.kdddy.cn/donghui/generalBusiness/generalQueryByTableName",
        type: "POST",
        data: {
          Data: "base_EdibleMushroomGrade",
          Condition: "Row_Status='0' AND VarietyID='" + _this.VarietyID + "'",
        },
        success: function (Result) {
          // _this.tableData = Result.Rows;
          _this.iJSONArray_VarietyGrade = new Array(); //清空数组中原有值
          _this.iJSONArray_VarietyGrade = Result;
        },
        complete: function (XMLHttpRequest) {
          requestPretreatment(XMLHttpRequest); //config/config.js 响应预检
        },
        dataType: "json",
      });
    },
    handleChange(value) {
      console.log(value);
    },
    getData() {
      const that = this;
      $.ajax({
        url: absolutepath() + "utils/city.json",
        type: "GET",
        success: function (data) {
          that.city = data;
        },
        dataType: "json",
      });
      $.ajax({
        headers: requestHeaders(),
        url: `${BASE_URL2}/generalBusiness/generalQueryByTableName`,
        type: "POST",
        data: {
          Data: "business_category",
          Condition: "Row_Status = '0'",
        },
        success: function (Result) {
          that.category = Result;
        },
        complete: function (XMLHttpRequest) {
          requestPretreatment(XMLHttpRequest);
        },
        dataType: "json",
      });
    },
    changeCity(arr, row) {
      //初始化
      row.ProvinceNumber = "";
      row.CityNumber = "";
      row.CountyNumber = "";
      row.TownNumber = "";
      row.VillageNumber = "";
      row.value2 = [];
      row.town = [];
      if (arr.length > 0) {
        row.ProvinceNumber = arr[0];
        row.CityNumber = arr[1];
        row.CountyNumber = arr[2];
        $.ajax({
          url: `${BASE_URL1}/getTownSelector?CountyNumber=${arr[2]}`,
          type: "GET",
          success: function (Result) {
            row.town = Result;
          },
          dataType: "json",
        });
      }
    },
    changeTown(arr, row) {
      row.TownNumber = arr[0] ? arr[0] : "";
      row.VillageNumber = arr[1] ? arr[1] : "";
    },
    handleLand(Data, row) {
      const _this = this;
      $.ajax({
        url: `${BASE_URL1}/landCertificateAction`,
        type: "POST",
        data: { Data },
        success: function (Result) {
          console.log(Result);
          if (Result.Status == "success") {
            _this.$message({
              message: "识别成功",
              type: "success",
            });
            row.Located = Result.located;
            row.Land_Number = Result.landNumber;
            row.Planting_Area = Result.UsufructArea;
          }
        },
        dataType: "json",
      });
    },
    add_land() {
      this.land.push({
        Traceability_Land_SerialNumber: "",
        ID_Number: this.form.ID_Number,
        Land_Number: "",
        ProvinceNumber: "",
        CityNumber: "",
        CountyNumber: "",
        TownNumber: "",
        VillageNumber: "",
        Located: "",
        Planting_Area: "",
        Category_SerialNumber: "",
        Land_Certificate: "",
        TownJSON: "",
        value1: [],
        town: [], //市区
        value2: [],
      });
    },
    remove_land() {
      if (this.land.length > 1) {
        this.land.pop();
      } else {
        this.$message({
          message: "不能在删除了",
          type: "warning",
        });
      }
    },
    //查询企业信息和个人信息
    submitFormxc(formName) {
      console.log(this.Unit);

      console.log(this.value1);
      console.log(this.value2);

      console.log(this.form);
      if (this.form.ID_Front == "") {
        this.$message.error("您未上传身份证");
        return;
      }
      if (this.form.Phone == "") {
        this.$message.error("您未填写手机号");
        return;
      }
      console.log(this.land);
      if (this.land[0].Land_Certificate == "") {
        this.$message.error("您未上传土地证");
        return;
      }
      if (this.VarietyID == "") {
        this.$message.error("请选择收购品种");
        return;
      }
      if (this.GradeID == "") {
        this.$message.error("请选择收购等级");
        return;
      }
      if (this.Unit == "") {
        this.$message.error("请选择收购单位");
        return;
      }
      if (this.PurchaseDate == "") {
        this.$message.error("请选择收购日期");
        return;
      }

      if (this.land[0].value1.length == 0) {
        this.$message.error("请选择省/市/区");
        return;
      }
      if (this.land[0].value2.length == 0) {
        this.$message.error("请选择乡镇/村");
        return;
      }

      // return;
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const _this = this;

          console.log(_this.land);
          console.log(_this.land[0].ID_Number);
          let a = _this.land[0].ID_Number;
          console.log(a);

          // return;
          $.ajax({
            headers: requestHeaders(),
            type: "POST",
            // url: `${BASE_URL2}/generalBusiness/generalPaginationQueryBySQLSerialNumber`,
            url: "https://service.kdddy.cn/donghui/generalBusiness/generalQueryByTableName",
            data: {
              Data: "business_traceability_farmer", //表名
              Condition: "Row_Status='0' And ID_Number=" + `${a}`,
            },
            success: function (Result) {
              console.log(Result, "csfz");
              if (Result.length == "") {
                _this.submitForm();
              } else {
                console.log(_this.land);
                let td = new Object();
                td.FarmerID = _this.form.ID_Number;
                td.LandCertificate = _this.land[0].Land_Certificate;
                td.LandNumber = _this.land[0].Land_Number;
                td.PurchaseLocation = _this.land[0].Located;

                let PurchaseEnterpriseID = sessionStorage.getItem(
                  "Enterprise_Info_SerialNumber"
                );
                console.log(PurchaseEnterpriseID);

                td.PurchaseEnterpriseID = PurchaseEnterpriseID;
                td.PurchaseDate = _this.PurchaseDate;
                console.log(td);
                let tdzb = new Object();
                tdzb.Unit = _this.Unit;
                tdzb.PurchasePrice = _this.PurchasePrice;
                tdzb.PurchaseQuantity = _this.PurchaseQuantity;
                tdzb.GradeID = _this.GradeID;
                tdzb.VarietyID = _this.VarietyID;

                console.log(tdzb);

                //子表结构
                let lArrayzb = new Array();
                lArrayzb.push(tdzb);
                let lJSONObject_base_EdibleMushroomPurchaseDetails =
                  new Object();
                lJSONObject_base_EdibleMushroomPurchaseDetails.base_EdibleMushroomPurchaseDetails =
                  lArrayzb; //换表
                td.Children = lJSONObject_base_EdibleMushroomPurchaseDetails;
                console.log(td);
                let lArray = new Array();
                lArray.push(td);
                let lJSONObject_business_traceability_farmer = new Object();
                lJSONObject_business_traceability_farmer.base_EdibleMushroomPurchase =
                  lArray;
                let lJSONObject_DataSet = new Object(); // Modify
                lJSONObject_DataSet.Add =
                  lJSONObject_business_traceability_farmer; //换表
                //套Add
                console.log(lJSONObject_DataSet);
                // return;
                $.ajax({
                  // headers: requestHeaders(),
                  // url: `${BASE_URL2}/generalBusiness/generalPaginationQueryBySQLSerialNumber`,
                  url: "https://service.kdddy.cn/donghui/clientOperation/generalSaveForClient",
                  type: "POST",
                  data: {
                    Data: JSON.stringify(lJSONObject_DataSet),
                  },
                  success: function (Result) {
                    console.log(Result);
                    if (Result.Status === "success") {
                      _this.$message.success("提交成功");
                      window.history.go(-1);
                    } else {
                      _this.$message.error("提交失败，请稍后再试");
                    }
                  },

                  complete: function (XMLHttpRequest) {
                    requestPretreatment(XMLHttpRequest); //config/config.js 响应预检
                  },
                  dataType: "json",
                });
              }
              //   _this.submitForm(Result);
            },
            complete: function (XMLHttpRequest) {
              //   requestPretreatment(XMLHttpRequest);
            },
            dataType: "json",
          });
        }
      });
    },
    // csfz() {

    // },
    submitForm(res) {
      const _this = this;
      console.log(_this.form);
      _this.form.TownJSON = "";
      //身份信息
      let sflArray = new Array();
      sflArray.push(_this.form);
      let lJSONObject_business_traceability_farmer = new Object();
      lJSONObject_business_traceability_farmer.business_traceability_farmer =
        sflArray; //换表

      console.log(_this.land);
      let td = new Object();
      td.FarmerID = _this.form.ID_Number;
      td.LandCertificate = _this.land[0].Land_Certificate;
      td.LandNumber = _this.land[0].Land_Number;
      td.PurchaseLocation = _this.land[0].Located;

      let PurchaseEnterpriseID = sessionStorage.getItem(
        "Enterprise_Info_SerialNumber"
      );
      console.log(PurchaseEnterpriseID);
      td.PurchaseEnterpriseID = PurchaseEnterpriseID;
      td.PurchaseDate = _this.PurchaseDate;
      console.log(td);
      let tdzb = new Object();
      tdzb.Unit = _this.Unit;
      tdzb.PurchasePrice = _this.PurchasePrice;
      tdzb.PurchaseQuantity = _this.PurchaseQuantity;
      tdzb.GradeID = _this.GradeID;
      tdzb.VarietyID = _this.VarietyID;

      console.log(tdzb);

      //子表结构
      let lArrayzb = new Array();
      lArrayzb.push(tdzb);
      let lJSONObject_base_EdibleMushroomPurchaseDetails = new Object();
      lJSONObject_base_EdibleMushroomPurchaseDetails.base_EdibleMushroomPurchaseDetails =
        lArrayzb; //换表
      td.Children = lJSONObject_base_EdibleMushroomPurchaseDetails;
      console.log(td);
      let lArray = new Array();
      lArray.push(td);
      lJSONObject_business_traceability_farmer.base_EdibleMushroomPurchase =
        lArray;

      //套Add
      let lJSONObject_DataSet = new Object();
      lJSONObject_DataSet.Add = lJSONObject_business_traceability_farmer;

      lJSONObject_business_traceability_farmer.business_traceability_land =
        _this.land;
      // console.log(lJSONObject_business_traceability_land);

      console.log(lJSONObject_DataSet);
      // return;
      $.ajax({
        // headers: requestHeaders(),
        // url: `${BASE_URL2}/generalBusiness/generalPaginationQueryBySQLSerialNumber`,
        url: "https://service.kdddy.cn/donghui/clientOperation/generalSaveForClient",
        type: "POST",
        data: {
          Data: JSON.stringify(lJSONObject_DataSet),
        },
        success: function (Result) {
          console.log(Result);
          //   if (Result.Status === "success") {
          //     _this.$message.success("提交成功");
          //     window.history.go(-1);
          //   } else {
          //     _this.$message.error("提交失败，请稍后再试");
          //   }
        },
        complete: function (XMLHttpRequest) {
          requestPretreatment(XMLHttpRequest); //config/config.js 响应预检
        },
        dataType: "json",
      });

      //   this.$refs[formName].validate((valid) => {
      //     if (valid) {
      //       that.loading = true;
      //       let business_traceability_land = [];
      //       let business_traceability_farmer = [
      //         {
      //           ID_Number: that.form.ID_Number,
      //           ID_Name: that.form.ID_Name,
      //           ID_Front: that.form.ID_Front,
      //           ID_Back: that.form.ID_Back,
      //           Phone: that.form.Phone,
      //           Validity_EndDate: that.form.Validity_EndDate,
      //           ID_Address: that.form.ID_Address,
      //           ProvinceNumber: that.form.ProvinceNumber,
      //           CityNumber: that.form.CityNumber,
      //           CountyNumber: that.form.CountyNumber,
      //           TownNumber: that.form.TownNumber,
      //           VillageNumber: that.form.VillageNumber,
      //           // TownJSON:JSON.stringify(that.form.town)
      //           TownJSON: "[]",
      //         },
      //       ];
      //       that.land.forEach((item) => {
      //         business_traceability_land.push({
      //           Traceability_Land_SerialNumber:
      //             item.Traceability_Land_SerialNumber,
      //           ID_Number: item.ID_Number,
      //           Land_Number: item.Land_Number,
      //           ProvinceNumber: item.ProvinceNumber,
      //           CityNumber: item.CityNumber,
      //           CountyNumber: item.CountyNumber,
      //           TownNumber: item.TownNumber,
      //           VillageNumber: item.VillageNumber,
      //           Located: item.Located,
      //           Planting_Area: item.Planting_Area,
      //           Category_SerialNumber: item.Category_SerialNumber,
      //           Land_Certificate: item.Land_Certificate,
      //           TownJSON: "[]",
      //           // TownJSON:JSON.stringify(item.town)
      //         });
      //       });
      //       $.ajax({
      //         headers: requestHeaders(),
      //         url: `${BASE_URL2}/generalBusiness/generalSave`,
      //         type: "POST",
      //         data: {
      //           Data: JSON.stringify({
      //             Add: {
      //               business_traceability_farmer,
      //               business_traceability_land,
      //             },
      //           }),
      // },
      //         success: function (res) {
      //           if (res.Status === "success") {
      //             that.$message.success("提交成功");
      //             window.history.go(-1);
      //           } else {
      //             that.$message.error("提交失败，请稍后再试");
      //           }
      //         },
      //         complete: function (XMLHttpRequest) {
      //           that.loading = false;
      //           requestPretreatment(XMLHttpRequest);
      //         },
      //         dataType: "json",
      //       });
      //     } else {
      //       that.$message({
      //         message: sumberError,
      //         type: "warning",
      //       });
      //       return false;
      //     }
      //   });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
  },
});
